package com.rokyinfo.pdm.config;

import com.rokyinfo.pdm.controller.BasicPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import static com.google.common.collect.Lists.newArrayList;
import static springfox.documentation.builders.PathSelectors.ant;


@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * Reference to logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerConfig.class);

    //@formatter:off
    @Bean
    public Docket pdmApi() {


        return new Docket(DocumentationType.SWAGGER_2)
                .securitySchemes(newArrayList(apiKey()))
                .securityContexts(newArrayList(securityContext()))
                .groupName("PDM APIs")
                .apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.basePackage(BasicPath.class.getPackage().getName()))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Roky Admin RESTFul APIs")
                .description("生产管理系统RESTFul APIs")
                .termsOfServiceUrl("http://www.rokyinfo.com")
                .contact(new Contact("袁志健", "https://github.com/yuanzj", "zhijian.yuan@rokyinfo.com"))
                .version("0.1").build();
    }


    @Bean
    SecurityContext securityContext() {
        AuthorizationScope[] scopes = {new AuthorizationScope("write", "write access"), new AuthorizationScope("read", "read access")};
        SecurityReference securityReference = SecurityReference.builder()
                .reference("pdm_auth")
                .scopes(scopes)
                .build();

        return SecurityContext.builder()
                .securityReferences(newArrayList(securityReference))
                .forPaths(ant("/api/v1/*.*"))
                .build();
    }


    @Bean
    SecurityScheme apiKey() {
        return new ApiKey("Authorization", "Authorization", "header");
    }


}
